package com.sz.biz;

import com.sz.common.base.dao.ext.ScriptDao;
import org.springframework.test.context.TestContext;
import org.springframework.test.context.support.AbstractTestExecutionListener;

import java.io.InputStream;
import java.net.URL;

/**
 * Package: com.sz.biz <br>
 * Function: TODO: ADD FUNCTION <br>
 * Author: Charles. <br>
 * Date: 2017-04-07 12:43:00.
 */
public class SqlScriptExecutionListener extends AbstractTestExecutionListener {

    public final int getOrder() {
        return 5000;
    }

    public SqlScriptExecutionListener() {
    }

    public void beforeTestClass(TestContext testContext) throws Exception {
        //初始化Spring context
        testContext.getApplicationContext();
        String clazzName = testContext.getTestClass().getSimpleName();
        String fileName = clazzName + "-before.sql";
        execute(testContext, fileName);
    }

    public void afterTestClass(TestContext testContext) throws Exception {
        testContext.getApplicationContext();
        String clazzName = testContext.getTestClass().getSimpleName();
        String fileName = clazzName + "-after.sql";
        execute(testContext, fileName);
    }

    protected void execute(TestContext testContext, String file) throws Exception {
        InputStream stream = null;if(file != null && file.length() > 0) {
            String sqlFile = "/mock-sql/" + file;
            URL url = testContext.getTestClass().getClass().getResource(sqlFile);
            if (url != null) {
                stream = testContext.getTestClass().getClass().getResourceAsStream(sqlFile);
            }
        }
        if (stream != null) {
            ScriptDao scriptDao = testContext.getApplicationContext().getBean(ScriptDao.class);
            scriptDao.executeScript(stream);
        }
    }
}
